import React, { forwardRef, useEffect, useState, useRef } from 'react';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
import axios from 'axios';
import { Modal, Form, Button, Input } from 'antd';
import style from './user.module.css';
const { list } = style;
const { Search } = Input;

const User = forwardRef((props, ref) => {
  // console.log(props, 'props');
  // console.log(ref, "ref");
  const addForm = useRef(null);
  const updateForm = useRef(null);
  const [current,setCurrent]=useState(null)
  const [userList, setUserList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [isVisible, setIsVisible] = useState(false);
  
  const getUser = () => {
    axios.get(`http://localhost:3004/users`).then((res) => {
      // console.log(res.data, 'res');
      setUserList(res.data);
    });
  };
  const onChangeUserList = (item) => {
    // console.log(item, "item");

    setTimeout(() => {
      // 变成同步处理方案
      setVisible(true);

      updateForm.current.setFieldsValue(item);
    }, 0);
    // 把每次更新的哪个 存下来
    setCurrent(item)
  };
  const onChange = (val) => {
    // console.log(val, 'v');
    const arr = userList.filter((item) => item.name.includes(val));
    // console.log(userList, 'userList');
    setUserList(arr);
  };
  const onDelUserList = (id) => {
    // console.log(id, '123');
    axios.delete(`http://localhost:3004/users/${id}`).then((res) => {
      getUser();
    });
  };

  useEffect(() => {
    getUser();
  }, []);
  return (
    <div>
      <Button
        type="primary"
        onClick={() => {
          setIsVisible(true);
          console.log(isVisible, 'isVisible');
        }}
      >
        添加用户
      </Button>

      <Modal
        visible={isVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setIsVisible(false);
        }}
        onOk={() => {
          console.log(addForm, '1');
          addForm.current
            .validateFields()
            .then((values) => {
              console.log(values);
              axios
                .post(`http://localhost:3004/users`, {
                  // username: values.username,
                  // password: values.password,
                  // name: values.name,
                  // phone: values.phone,
                  // city: values.city,
                  // job_unit: values.job_unit,
                  // industry: values.industry,
                  ...values,
                })
                .then((res) => {
                  console.log(res.data, 'data');
                });
              setTimeout(() => {
                // setUserList([...userList, res.data]);
                getUser();
              }, 500);
              setIsVisible(false);
              addForm.current.resetFields();
            })
            .catch((err) => {
              console.log(err);
            });
        }}
      >
        <Form ref={addForm} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '用户名不能为空' }]}
          >
            <Input placeholder="填写您的用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '密码不能为空' }]}
          >
            <Input placeholder="填写您的密码" />
          </Form.Item>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '姓名不能为空' }]}
          >
            <Input placeholder="填写您的姓名" />
          </Form.Item>
          <Form.Item name="phone" label="手机">
            <Input placeholder="填写您的手机号码" />
          </Form.Item>
          <Form.Item name="city" label="所在城市">
            <Input placeholder="填写您的所在城市" />
          </Form.Item>
          <Form.Item name="job_unit" label="所在单位">
            <Input placeholder="填写您的所在单位" />
          </Form.Item>
          <Form.Item name="industry" label="行业领域">
            <Input placeholder="填写您的行业领域" />
          </Form.Item>
        </Form>
      </Modal>
      <Search
        placeholder="搜索姓名"
        onSearch={onChange}
        style={{ width: '85%', marginLeft: '50px' }}
      />
      <div>
        <p style={{ textAlign: 'center', marginTop: '20px' }}>
          共有{userList.length}条符合条件记录
        </p>
        <ul>
          {userList.map((item) => (
            <li key={item.id} className={list} style={{ textAlign: 'center' }}>
              <div style={{ textAlign: 'left', margin: '0 45%', width: '30%' }}>
                <p>
                  姓名 : <span style={{ marginLeft: '20px' }}>{item.name}</span>{' '}
                </p>
                <p>
                  手机 :{' '}
                  <span style={{ marginLeft: '20px' }}>{item.phone}</span>
                </p>
                <p>
                  城市 : <span style={{ marginLeft: '20px' }}>{item.city}</span>
                </p>
                <p>
                  行业 :{' '}
                  <span style={{ marginLeft: '20px' }}>{item.industry}</span>
                </p>
                <p>
                  单位 :{' '}
                  <span style={{ marginLeft: '20px' }}>{item.job_unit}</span>
                </p>
              </div>
              <span
                style={{
                  color: '#f00',
                  cursor: 'pointer',
                }}
                onClick={() => onDelUserList(item.id)}
              >
                <DeleteOutlined /> 删除
              </span>
              <span
                style={{
                  color: '#f00',
                  cursor: 'pointer',
                  marginLeft: '20px',
                }}
                onClick={() => onChangeUserList(item)}
              >
                <EditOutlined /> 编辑
              </span>
            </li>
          ))}
        </ul>
      </div>
      <Modal
        visible={visible}
        title="编辑用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setVisible(false);
        }}
        onOk={() => {
          updateForm.current
            .validateFields()
            .then((values) => {
              console.log(values);
              console.log(current);
              axios.patch(`http://localhost:3004/users/${current.id}`, {
                ...values
              });
              setTimeout(() => {
                getUser();
              }, 500);
              setVisible(false);
            })
            .catch((err) => {
              console.log(err);
            });
        }}
      >
        <Form ref={updateForm} layout="vertical">
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '姓名不能为空' }]}
          >
            <Input placeholder="填写您的姓名" />
          </Form.Item>
          <Form.Item name="phone" label="手机">
            <Input placeholder="填写您的手机号码" />
          </Form.Item>
          <Form.Item name="city" label="所在城市">
            <Input placeholder="填写您的所在城市" />
          </Form.Item>
          <Form.Item name="job_unit" label="所在单位">
            <Input placeholder="填写您的所在单位" />
          </Form.Item>
          <Form.Item name="industry" label="行业领域">
            <Input placeholder="填写您的行业领域" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
});

export default User;
